package com.yangjun.controller.realtimeLiveAnalysis.flowAnalysis;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.dao.mybatis.mapper.realtimeLiveAnalysis.flowAnalysisMapper;
import com.yangjun.entity.realtimeliveAnalysis.DvSearchKeyword;
import com.yangjun.entity.realtimeliveAnalysis.DvSearchKeywordNullResult;
import com.yangjun.entity.realtimeliveAnalysis.DvSearchKeywordURL;
import com.yangjun.utils.DvUtils;
/**
 * 
 * @ClassName pathAnalysisController
 * @Description 实时直播的流量分析板块
 * @author yangjun
 * @Date 2016年10月14日 上午10:35:36
 * @version 1.0.0
 */
@Controller
@RequestMapping("/realtimeLiveAnalysis/flowAnalysis/path")
public class PathAnalysisController {
	
	@Autowired
    private flowAnalysisMapper flowAnalysisMapper;
	
	/**
	 * @Description 获取路径分析列表各个页面类型的访客数以及占比
	 * @param siteid
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:37:56
	 */
	@RequestMapping("/getVisitTypeVisitors")
	@ResponseBody
	public Map<String,Map<String,Object>> getVisitTypeVisitors(
			@RequestParam(value = "siteid",required = false)String siteid,
			HttpServletResponse response){
    	Map<String,Map<String,Object>> resultMap = Maps.newHashMap();
		String typeName = null;
		//根据平台参数获取每个平台的访客数
		List<Map<String,Object>> visitTypeVisitors = flowAnalysisMapper.queryVisitTypeVisitors(Integer.parseInt(siteid));
		//计算总人数
		int sumVisitors = getSumVisitors(visitTypeVisitors);
		
		for(Map<String,Object> map : visitTypeVisitors){
			float proportion = 0;
			Map<String,Object> visitorsMap = Maps.newHashMap();
			visitorsMap.put("visitors", map.get("VISITORS"));
			//如果当前访问的页面类型为空即为直接访问否则获取对应的页面类型
			if( map.get("TYPE")==null){
				typeName = "direct";
			}else{
				typeName = map.get("TYPE").toString();
			}
			//计算占比
			if(map.get("VISITORS")!=null){
				float i = Float.parseFloat(String.valueOf(map.get("VISITORS")));
				proportion = (i/sumVisitors)*100;
			}
			//保留两位小数
			visitorsMap.put("proportion", String.format("%.2f", proportion));
			resultMap.put(typeName, visitorsMap);
		}
		return resultMap;
	}
	
	/**
	 * 
	 * @Description 获取页面类型渠道来源去向的数据
	 * @param siteid
	 * @param pagetype
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:34:33
	 */
	@RequestMapping("/getSourceAndDirection")
	@ResponseBody
	public Map<String,List<Map<String,Object>>> getSourceAndDirection(
			@RequestParam(value = "siteid",required = false)String siteid,
			@RequestParam(value = "pagetype",required = false)String pagetype,
			HttpServletResponse response){
		Map<String,List<Map<String,Object>>> resultMap = Maps.newHashMap();
		//根据平台参数siteid和页面类型参数pagetype获取数据
		List<Map<String,Object>> lastTypeVisitors = flowAnalysisMapper.querySourceAndDirection(Integer.parseInt(siteid), pagetype, "last");
		List<Map<String,Object>> nextTypeVisitors = flowAnalysisMapper.querySourceAndDirection(Integer.parseInt(siteid), pagetype, "next");
		resultMap.put("last",getPathMap(lastTypeVisitors,"last"));
		resultMap.put("next",getPathMap(nextTypeVisitors,"next"));
		return resultMap;
	}
	/**
	 * @Description 获取页面访问排行数据
	 * @param siteid
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:40:57
	 */
	@RequestMapping("/getVisitTypeSituation")
	@ResponseBody
	public Map<String,Object> getVisitTypeSituation(
			@RequestParam(value = "siteid",required = false)String siteid,
			HttpServletResponse response){
		
		Map<String,Object> resultMap = Maps.newHashMap();
		List<String> legendList = Lists.newArrayList();
		List<Map<String,String>> pageTypeList = Lists.newArrayList();
		String typeName = null;
		//获取当前访问的页面类型的数据
		List<Map<String,Object>> visitPageTypeList = flowAnalysisMapper.queryVisitTypeSituation(Integer.parseInt(siteid));
		for(Map<String,Object> map : visitPageTypeList){
			Map<String,String> pageTypeMap = Maps.newHashMap();
			Map<String,Object> dataMap = Maps.newHashMap();
			//如果当前访问页面类型为空即为直接访问否则直接获取对应的页面类型
			if( map.get("VISIT_TYPE")==null){
				typeName = "direct";
			}else{
				typeName = map.get("VISIT_TYPE").toString();
			}
			//不同页面类型的访客数（饼图需要该种格式）
			pageTypeMap.put("name", DvUtils.getPageType(typeName));
			pageTypeMap.put("value", map.get("VISITORS").toString());
			pageTypeList.add(pageTypeMap);
			//图例对应的中文名称
			legendList.add(DvUtils.getPageType(typeName));
			//页面类型的跳出率，平均访问时长，访问类型，访客数
			dataMap.put("jump_rate", map.get("JUMP_RATE")==null?0:map.get("JUMP_RATE").toString());
			dataMap.put("avg_visitlength", map.get("AVG_VISITLENGTH")==null?0:map.get("AVG_VISITLENGTH").toString());
			dataMap.put("visit_type", map.get("VISIT_TYPE")==null?null:map.get("VISIT_TYPE").toString());
			dataMap.put("visitors", map.get("VISITORS")==null?0:map.get("VISITORS").toString());
			resultMap.put(dataMap.get("visit_type").toString(), dataMap);
		}
		//如果获取的页面类型为空则设置为默认值防止前端获取不了对象
		for(String pagetype : DVConstants.PAGE_TYPE){
			Map<String,Object> dataMap = Maps.newHashMap();
			if(resultMap.get(pagetype)==null){
				dataMap.put("jump_rate",0);
				dataMap.put("avg_visitlength",0);
				dataMap.put("visit_type", null);
				dataMap.put("visitors", 0);
				resultMap.put(pagetype, dataMap);
			}
		}
		resultMap.put("lengend", legendList);
		resultMap.put("data", pageTypeList);
		return resultMap;
	}
	/**
	 * @Description 获取页面访问排行的详细路径
	 * @param siteid
	 * @param pagetype
	 * @param pageNum
	 * @param pageSize
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:46:33
	 */
	@RequestMapping("/getVisitPath")
	@ResponseBody
	public PageInfo<Map<String, Object>> getVisitPath(
			@RequestParam(value = "siteid",required = false)String siteid,
			@RequestParam(value = "pagetype",required = false)String pagetype,
    		@RequestParam(value = "pageNum",required = false)String pageNum,
    		@RequestParam(value = "pageSize",required = false)String pageSize,
			HttpServletResponse response){
		//需要分页，从前端获取当前页码以及显示的页面大小
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize),true,true,true);
    	//根据平台参数以及页面类型参数获取分页数据
    	PageInfo<Map<String, Object>> page = new PageInfo(flowAnalysisMapper.queryVisitPath(Integer.parseInt(siteid),pagetype));
		return page;
	}
	/**
	 * @Description 获取热搜关键词
	 * @param siteid
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:47:56
	 */
	@RequestMapping("/getHotSearchKeyword")
	@ResponseBody
	public Map<String,Object> getHotSearchKeyword(
			@RequestParam(value = "siteid",required = false)String siteid,
			HttpServletResponse response){
    	Map<String,Object> resultMap = Maps.newHashMap();
    	//根据不同的标识和平台参数获取对应的数据
    	List<Map<String,Object>> oneHourList = flowAnalysisMapper.queryHotSearchkeyword(siteid,"last_one_hour", 25);
    	List<Map<String,Object>> oneDayList = flowAnalysisMapper.queryHotSearchkeyword(siteid,"last_one_day", 25);
    	resultMap.put("oneHourSearchKeyword",DvUtils.randomList(getKeywordList(oneHourList)));
    	resultMap.put("oneDaySearchKeyword", DvUtils.randomList(getKeywordList(oneDayList)));
    	//要把最大的访客数提供给前端
    	resultMap.put("oneHourMaxVisitors",oneHourList.size()>0? oneHourList.get(0).get("VISITORS"):0);
    	resultMap.put("oneDayMaxVisitors",	oneDayList.size()>0?  oneDayList.get(0).get("VISITORS"):0);
		return resultMap;
	}
	/**
	 * @Description 获取搜索关键词
	 * @param siteid
	 * @param pageNum
	 * @param pageSize
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:49:07
	 */
	@RequestMapping("/getSearchKeyword")
	@ResponseBody
	public Map<String,Object> getSearchKeyword(
			@RequestParam(value = "siteid",required = false)String siteid,
    		@RequestParam(value = "pageNum",required = false)String pageNum,
    		@RequestParam(value = "pageSize",required = false)String pageSize,
			HttpServletResponse response) throws UnsupportedEncodingException{
    	Map<String,Object> resultMap = Maps.newHashMap();
    	int sum = 0;
    	//根据平台参数获取关键词数据默认取top100,之后可以根据前台设置top值
    	List<DvSearchKeyword> DvSearchKeywordList = flowAnalysisMapper.querySearchkeyword(siteid, 100);
    	//获取总的搜索人数
    	for(DvSearchKeyword dvSearchKeyword : DvSearchKeywordList){
    		sum+=dvSearchKeyword.getSearchNum();
    	}
    	//获取分页数据
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize),true,true,true);
    	PageInfo<DvSearchKeyword> page = new PageInfo<DvSearchKeyword>(flowAnalysisMapper.querySearchkeyword(siteid, 100));
    	resultMap.put("page", page);
    	resultMap.put("sum", sum);
    	//获取最大的搜索人数
    	resultMap.put("max", DvSearchKeywordList.get(0).getSearchNum());
    	return resultMap;
	}
	/**
	 * @Description 获取搜索结果为空数据
	 * @param siteid
	 * @param pageNum
	 * @param pageSize
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:52:16
	 */
	@RequestMapping("/getNullResult")
	@ResponseBody
	public Map<String,Object> getNullResult(
			@RequestParam(value = "siteid",required = false)String siteid,
    		@RequestParam(value = "pageNum",required = false)String pageNum,
    		@RequestParam(value = "pageSize",required = false)String pageSize,
			HttpServletResponse response) throws UnsupportedEncodingException{
    	Map<String,Object> resultMap = Maps.newHashMap();
    	//根据默认值获取搜索结果为空的数据默认是top50按搜索人数排序
    	Integer max = 0;
    	List<DvSearchKeywordNullResult> nullResultList= flowAnalysisMapper.queryNullResult(siteid);
    	if(nullResultList.size()>0){
    		max=nullResultList.get(0).getSearchNum();
    	}
    	resultMap.put("max",max );
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize),true,true,true);
    	PageInfo<DvSearchKeywordNullResult> page = new PageInfo<DvSearchKeywordNullResult>(flowAnalysisMapper.queryNullResult(siteid));
    	resultMap.put("page", page);
    	return resultMap;
	}
	/**
	 * @Description 获取搜索关键词点击的链接
	 * @param siteid
	 * @param searchKeyword
	 * @param pageNum
	 * @param pageSize
	 * @param response
	 * @author yangjun
	 * @Date 2016年10月14日 上午10:54:58
	 */
	@RequestMapping("/getSearchKeywordURL")
	@ResponseBody
	public PageInfo getSearchKeywordURL(
			@RequestParam(value = "siteid",required = false)String siteid,
    		@RequestParam(value = "searchKeyword",required = false)String searchKeyword,
    		@RequestParam(value = "pageNum",required = false)String pageNum,
    		@RequestParam(value = "pageSize",required = false)String pageSize,
			HttpServletResponse response){
    	Map<String,Object> resultMap = Maps.newHashMap();
    	//需要分页
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize),true,true,true);
    	PageInfo<DvSearchKeywordURL> page = new PageInfo<DvSearchKeywordURL>(flowAnalysisMapper.querySearchkeywordURL(siteid, searchKeyword));
    	return page;
	}
	//规范前台小写获取数据
	public List<Map<String,String>> getKeywordList(List<Map<String,Object>> list){
    	List<Map<String,String>> keywordList = Lists.newArrayList();
	 	for(Map<String,Object> map : list){
        	Map<String,String> keywordMap = Maps.newHashMap();
    		keywordMap.put("name", map.get("SEARCHKEYWORD").toString());
    		keywordMap.put("value", map.get("VISITORS").toString());
    		keywordList.add(keywordMap);
    	}
		return keywordList;
		
	}
	//计算总人数
	public int getSumVisitors(List<Map<String,Object>> list){
		int sumVisitors = 0;
		for(Map<String,Object> map : list){
			if(map.get("VISITORS")!=null){
				sumVisitors += Integer.parseInt(String.valueOf(map.get("VISITORS"))); 
			}
		}
		return sumVisitors;
	}
	public List<Map<String,Object>> getPathMap(List<Map<String,Object>> vmap,String index){
		List<Map<String,Object>> resultList = Lists.newArrayList();
		String typeName = null;
		//算总人数	
		int sumVisitors = getSumVisitors(vmap);
		for(Map<String,Object> map : vmap){
			float proportion = 0;
			Map<String,Object> visitorsMap = Maps.newHashMap();
			visitorsMap.put("visitors", map.get("VISITORS"));
			if( map.get("TYPE")==null&&index=="last"){
				typeName = "direct";
			}else if( map.get("TYPE")==null&&index=="next"){
				typeName = "out";
			}else{
				typeName = map.get("TYPE").toString();
			}
			visitorsMap.put("type",DvUtils.getPageType(typeName));
			if(map.get("VISITORS")!=null){
				float i = Float.parseFloat(String.valueOf(map.get("VISITORS")));
				proportion = (i/sumVisitors)*100;
			}
			visitorsMap.put("proportion", String.format("%.2f", proportion));
			resultList.add(visitorsMap);
		}
		return resultList;
	}
}
